<template>
	<view class="container">
		<view class="content">
			<owner-info :item="carInfo"></owner-info>
			<view class="order-info">
				<text class="txt1">订单信息</text>
				<view class="txt2">
					<text class="txt2-1">销售</text>
					<text class="txt2-2">{{store.currentUser.name}}</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">业务渠道</text>
					<text class="txt2-2" style="width:140rpx;border-bottom: 1rpx solid #767676;text-align: center;"
						v-if="businessTypeTxt == '点击选择'" @click="selectShow = true">
						{{businessTypeTxt}}
					</text>
					<text class="txt2-2" style="width:140rpx;border-bottom: 1rpx solid #767676;text-align: center;"
						v-else @click="selectShow = true">
						{{businessTypeTxt}}
					</text>
				</view>
			</view>
		</view>
		<view class="add-info">
			<view class="title">
				<text class="txt">车辆照片(正面、侧面45°、侧后45°、背面)</text>
				<image class="add" src="https://peixin.peiyu.online/xmk/images/添加.png" mode="widthFix"
					@click="uploadImg"></image>
			</view>
			<view class="photo-content">
				<template v-for="(item,index) in photoTemPath" :key="index">
					<image class="photo" :src="item" mode="aspectFill" @click="previewImage(photoTemPath,index)">
					</image>
				</template>
			</view>
		</view>
		<view class="add-info">
			<view class="title">
				<text class="txt">服务项目</text>
				<image class="add" src="https://peixin.peiyu.online/xmk/images/添加.png" mode="heightFix"
					@click="add_service"></image>
			</view>
			<u-swipe-action>
				<u-swipe-action-item :options="options" v-for="(item,index) in store.serviceItem"
					:key="item.serviceItemId" @click="del_service(index)">
					<view v-if="store.serviceItem" class="chosenContent">
						<view class="top">
							<view class="serv">
								<text class="service">{{item.serviceName}}</text>
								<text class="product">{{item.productName}}</text>
							</view>
						</view>
						<view style="display: flex;align-items: center; padding: 5rpx 0;">
							<text class="price1">{{item.servicePrice + item.productPrice}}</text>
							<text class="price2">元</text>
						</view>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
		</view>

		<view class="btn" @click="pushOrder">
			加入订单
		</view>

		<up-picker closeOnClickOverlay :show="selectShow" :columns="businessList" keyName="label"
			@cancel="selectShow=false" @confirm="confirm" @close="selectShow=false">
		</up-picker>
	</view>

</template>

<script setup>
	import {
		BASE_URL
	} from "../../../../utils/request.js"
	import {
		reactive,
		ref,
	} from 'vue';
	import {
		onLoad,
		onShow,
	} from "@dcloudio/uni-app";
	import {
		useMainStore
	} from '@/utils/store.js';
	import {
		api_get_order_easy_info,
		api_orderService_add,
		api_saleOrder_update,
		api_serviceItem_delete,
		api_orderSettlement_add,
		api_orderSettlement_update,
		api_saleOrder_getSaleOrderInfo,
		api_businessType_list
	} from "../../../../apis/apis.js"

	const photoTemPath = ref(""); //照片
	const store = ref(useMainStore()); //状态存储
	const options = reactive([{ //左滑操作栏
		text: '删除',
		style: {
			backgroundColor: '#f56c6c'
		}
	}]);
	const carInfo = ref({}); //订单简易信息
	const totalPrice = ref(0);
	const selectValue = ref(0);
	const range = ref([]);
	const businessTypeTxt = ref("点击选择");
	const businessTypeId = ref(-1);
	const businessList = ref([]);
	const selectShow = ref(false);


	//点击数据选择器的确定
	const confirm = (e) => {
		console.log('confirm', e);
		selectShow.value = false;
		businessTypeId.value = e.value[0].id;
		businessTypeTxt.value = e.value[0].label;
	};


	//添加本地图片
	const uploadImg = () => {
		uni.chooseImage({
			count: 4,
			sizeType: ['original', 'compressed'],
			sourceType: ['album'], //这要注意，camera掉拍照，album是打开手机相册
			success: (res) => {
				console.log("图片", res);
				photoTemPath.value = res.tempFilePaths;
			}
		})
	};


	//上传单个图片  被upload_image调用
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				mask: true,
				title: "上传图片中"
			})
			let a = uni.uploadFile({
				url: `${BASE_URL}/file/upload`,
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				success: (res) => {
					resolve(res);
					console.log("上传成功", JSON.parse(res.data).data)
					store.value.set_orderCarImage(JSON.parse(res.data).data); //存到pinia
					uni.hideLoading();
				},
				fail: (err) => {
					console.log("上传失败", err);
					uni.hideLoading();
				},
				complete: (msg) => {
					console.log("上传结束");
					uni.hideLoading();
				}
			});
		});
	};

	//上传所有图片
	const upload_image = async (list) => {
		//上传图片
		for (let i = 0; i < list.length; i++) {
			try {
				await uploadFilePromise(list[i]);
			} catch (e) {
				uni.showToast({
					title: e.msg,
					icon: "none"
				});
			}
		}

	}

	//点击预览图片
	const previewImage = (photoTemPath, index) => {
		uni.previewImage({
			current: index,
			urls: photoTemPath
		});
	};

	// 添加服务
	const add_service = async () => {
		try {
			let res = await api_saleOrder_getSaleOrderInfo({ //确认哪个订单添加服务
				saleId: store.value.orderId
			});
			uni.navigateTo({
				url: `/pages/salesman/new-order/service-classify/service-classify?orderServiceId=${res.data.orderService.orderServiceId}`,
			});
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
	};

	//删除服务
	const del_service = (index) => {
		uni.showModal({
			title: '温馨提示',
			content: '确定要删除吗？',
			success: async (res) => {
				if (res.confirm) {
					let id = store.value.serviceItem[index].serviceItemId;
					console.log(id);
					store.value.delete_serviceItem(index); //删除所要删除的服务
					try {
						await api_serviceItem_delete({
							serviceItemId: id
						});
						console.log("选择的服务项目", store.value.serviceItem);
					} catch (e) {
						uni.showToast({
							title: e.msg,
							icon: "none"
						});
					}
				}
			}
		})
	};

	//加入订单
	const pushOrder = async () => {
		console.log("选择的服务项目", store.value.serviceItem);
		if (photoTemPath.value.length == 4 && store.value.serviceItem != [] && businessTypeId.value != -1) {
			try {
				//上传图片
				try {
					await upload_image(photoTemPath.value);
				} catch (e) {
					uni.showToast({
						title: e.msg,
						icon: "none"
					});
				}
				//修改支付状态
				try {
					await api_orderSettlement_update({
						orderSettlementId: carInfo.value.orderSettlementId,
						amountDue: totalPrice.value
					});
				} catch (e) {
					uni.showToast({
						title: e.msg,
						icon: "none"
					});
				}
				//完善订单
				try {
					await api_saleOrder_update({
						saleId: store.value.orderId,
						buildStatus: 1,
						images: JSON.stringify(store.value.orderCarImage),
						businessType: businessTypeId.value
					});
				} catch (e) {
					uni.showToast({
						title: e.msg,
						icon: "none"
					});
				}
			} catch (e) {
				uni.showToast({
					title: "出错了,无法生成订单",
					icon: "none"
				});
			}

			uni.reLaunch({
				url: "/pages/salesman/index/index",
				success: () => {
					uni.showToast({
						title: "加入订单成功"
					});
					console.log();
				}
			});
		} else {
			uni.showToast({
				title: "请完善订单",
				icon: "error"
			});
			return;
		}
	};


	onLoad(async () => {
		//获取订单简单信息
		try {
			let res = await api_get_order_easy_info({
				saleId: store.value.orderId
			});
			carInfo.value = res.data;
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
		//获取渠道
		try {
			let res = await api_businessType_list();
			let li = [];
			li.push(res.data.map(item => ({
				id: item.id,
				label: item.businessName
			})))
			businessList.value = li;
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
	})


	onShow(async () => {
		totalPrice.value = 0;
		if (store.value.serviceItem.length > 0) {
			if (store.value.serviceItem[0].flag) { //flag是否为true
				try {
					await api_serviceItem_delete({ //是就删除这项
						serviceItemId: store.value.serviceItem[0].serviceItemId,
					});
					store.value.serviceItem.splice(0, 1);
				} catch (e) {
					uni.showToast({
						title: e.msg,
						icon: "none"
					});
				}
			}
			for (let i = 0; i < store.value.serviceItem.length; i++) {
				totalPrice.value += (store.value.serviceItem[i].servicePrice + store.value.serviceItem[i]
					.productPrice)
			}
		}

		console.log("选择的服务项目", store.value.serviceItem);
		console.log("总价", totalPrice.value)
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: calc(calc(env(safe-area-inset-bottom)) + 10rpx);

		.content {
			display: flex;
			flex-direction: column;
			align-items: center;
			background-color: #ededf4;
			width: 750rpx;
			padding-top: 36rpx;
			padding-bottom: 50rpx;

			.order-info {
				background-color: $main-background-color;
				width: 700rpx;
				display: flex;
				flex-direction: column;
				align-items: left;
				gap: 10rpx;
				margin-top: 50rpx;

				.txt1 {
					font-family: Alibaba_PuHuiTi_Medium;
					font-weight: 500;
					font-size: 34rpx;
					color: $font-primary-color;
				}

				.txt2 {
					display: flex;
					align-items: center;

					.txt2-1 {
						width: 160rpx;
						font-family: Alibaba_PuHuiTi_Light;
						font-weight: 300;
						font-size: 34rpx;
						color: $font-primary-color;
						margin-right: 30rpx;
					}

					.txt2-2 {
						font-family: Alibaba_PuHuiTi_Light;
						font-weight: 300;
						font-size: 36rpx;
						color: $font-sub-color;
					}
				}
			}
		}

		.add-info {
			margin-top: 50rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.title {
				width: 700rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.txt {
					font-family: Alibaba_PuHuiTi_Medium;
					font-weight: 500;
					font-size: 34rpx;
					color: $font-primary-color;
				}

				.add {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.photo-content {
				width: 700rpx;
				display: flex;
				justify-content: left;
				align-items: center;
				gap: 6.6rpx;

				.photo {
					width: 170rpx;
					height: 170rpx;
					margin-top: 32rpx;
				}
			}

			.chosenContent {
				width: 700rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: left;

				border-bottom: 1rpx solid $border-color;

				.top {
					padding-top: 20rpx;
					width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.serv {
						display: flex;
						align-items: center;

						.service {
							font-family: Alibaba_PuHuiTi_Light;
							font-weight: 300;
							font-size: 34rpx;
							color: $font-primary-color;
							margin-right: 10rpx;
						}

						.product {
							font-family: Alibaba_PuHuiTi_Light;
							font-weight: 300;
							font-size: 34rpx;
							color: $font-sub-color;
						}
					}
				}

				.price1 {
					font-family: Alibaba_PuHuiTi_Thin;
					font-weight: 250;
					font-size: 34rpx;
					color: #FF602B;
					width: 84rpx;
					text-align: center;
				}

				.price2 {
					font-family: Alibaba_PuHuiTi_Light;
					font-weight: 300;
					font-size: 34rpx;
					color: #FF602B;
				}
			}
		}

		.btn {
			width: 700rpx;
			height: 80rpx;
			border-radius: 10rpx;
			overflow: hidden;
			background-color: $primary-color;
			font-family: Alibaba_PuHuiTi_Regular;
			font-weight: 400;
			font-size: 38rpx;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 50rpx;
		}
	}
</style>